package com.cgc.venus.server.log.service;

import com.cgc.venus.server.core.base.AbstractBaseService;
import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.utils.DateUtil;
import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.log.bean.OperLog;
import com.cgc.venus.server.log.inter.OperLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by 业哥 on 2017/11/20.
 */
@Service
public class OperLogServiceImpl extends AbstractBaseService implements OperLogService{


    @Autowired
    private JdbcTemplate jdbcTemplate;
    private final int PAGE_SIZE=10;
    /**
     * 查询操作日志类型
     * @return
     */
    @Override
    public List queryOperLogType() throws VenusException{
        String sql="select Fun_level_one f1,Fun_level_two f2,group_concat(Oper_type) f3 from t_oper_log_par GROUP BY Fun_level_one,Fun_level_two;";
        List<Map<String, Object>> r=jdbcTemplate.queryForList(sql);
        List l1=new ArrayList();//一级list
        List l2=null;//二级list
        List l3=null;//三级list
        Map<String, Object> m1=null;//一级map
        Map<String, Object> m2=null;//二级map
        Map<String, Object> m3=null;//三级map
        Map<String, Object> mTmp=new HashMap<String, Object>();
        mTmp.put("label","全部");
        mTmp.put("value", "全部");
        l1.add(mTmp);
        String f1Tmp="";
        if(r!=null&&r.size()>0){
            for(Map<String, Object> m:r){
                String f1=m.get("f1").toString();
                String f2=m.get("f2").toString();
                String f3=m.get("f3").toString();
                //添加第一级 start
                if(!f1.equals(f1Tmp)){
                    //新起一个1级
                    m1=new HashMap<String, Object>();
                    m1.put("value", f1);
                    m1.put("label", f1);
                    l1.add(m1);
                    f1Tmp=f1;
                    l2=new ArrayList();
                    mTmp=new HashMap<String, Object>();
                    mTmp.put("label","全部");
                    mTmp.put("value", "全部");
                    l2.add(mTmp);
                    m1.put("children",l2);
                }else{
                    //旧的
                    l2= (List) m1.get("children");
                }
                //添加第一级 end
                //添加第二级 start
                m2=new HashMap<String, Object>();
                m2.put("value", f2);
                m2.put("label", f2);
                l2.add(m2);
                //添加第二级 start
                //添加第三级 start
                l3=new ArrayList();
                m2.put("children", l3);
                String[] f3s=f3.split(",");
                int i0=0;
                for(String f3Tmp:f3s){
                    if(i0==0){
                        m3=new HashMap<String, Object>();
                        m3.put("value", "全部");
                        m3.put("label", "全部");
                        l3.add(m3);
                    }
                    m3=new HashMap<String, Object>();
                    m3.put("value", f3Tmp);
                    m3.put("label", f3Tmp);
                    l3.add(m3);
                    i0++;
                }
                //添加第三级 start
            }
        }
        return l1;
    }

    @Override
    public List queryAppLog(String appName) throws VenusException {
        String sql="SELECT date_format(tol.Create_time,'%y-%m-%d %T') time, concat(tol.duration, 'ms') duration, tolp.Oper_type f3, tol.`Status` sts, tu.`name` uname, tol.Oper_Object_name FROM t_oper_log tol LEFT JOIN t_oper_log_par tolp ON tol.Oper_log_par = tolp.id LEFT JOIN t_user tu ON tu.id = tol.`User` WHERE tol.Oper_Object_name LIKE ? ORDER BY time DESC";
        List<Object> obj=new ArrayList<Object>();
        //obj.add(appName.substring(0,appName.indexOf(":")) + "%");
        obj.add("%" + appName + "%");
        List list=this.jdbcTemplate.queryForList(sql,obj.toArray());
        return list;
    }

    @Override
    public OperLog queryAppLog(String operType, String status, String timeStart, String timeEnd, String queryKey, int currentPage,String userId) throws VenusException {
        OperLog operLog=new OperLog(new ArrayList(),0);
        if(StringUtil.isEmpty(operType)){
            return operLog;
        }
        if(StringUtil.isEmpty(status)){
            return operLog;
        }
        if(StringUtil.isEmpty(timeStart)){
            return operLog;
        }
        if(StringUtil.isEmpty(timeEnd)){
            return operLog;
        }

        //判断是否超级管理员 超级管理员查询所有
        //解析操作类型
        String f1="全部";
        String f2="全部";
        String f3="全部";
        String[] operTypes=operType.split(",");
        int i=0;
        for(String str:operTypes){
            if(i==0){
                f1=str;
            }
            if(i==1){
                f2=str;
            }
            if(i==2){
                f3=str;
            }
            i++;
        }

        String sql0="SELECT count(*) num FROM t_oper_log tol LEFT JOIN t_oper_log_par tolp ON tol.Oper_log_par = tolp.id LEFT JOIN t_user tu ON tu.id = tol.`User` WHERE tol.Create_time BETWEEN ? AND ?";
        String sql1="SELECT date_format(tol.Create_time,'%y-%m-%d %T') time, concat(tol.duration, 'ms') duration, tolp.Fun_level_one f1, tolp.Fun_level_two f2, tolp.Oper_type f3, tol.Oper_Object_name content, tol.`Status` sts, tu.`name` uname FROM t_oper_log tol LEFT JOIN t_oper_log_par tolp ON tol.Oper_log_par = tolp.id LEFT JOIN t_user tu ON tu.id = tol.`User` WHERE tol.Create_time BETWEEN ? AND ?";
        String sql2="ORDER BY time DESC LIMIT ?, ?";
        List<Object> obj=new ArrayList<Object>();
        try {
            obj.add(DateUtil.dealDateFormat1(timeStart));
            obj.add(DateUtil.dealDateFormat1(timeEnd));
        } catch (ParseException e) {
            throw new VenusException(VenusResponseStatus.LOG_EXCEPTION, "时间格式有误!");
        }
        if(!"全部".equals(f1)){
            sql0+=" AND tolp.Fun_level_one = ?";
            sql1+=" AND tolp.Fun_level_one = ?";
            obj.add(f1);
        }
        if(!"全部".equals(f2)){
            sql0+=" AND tolp.Fun_level_two = ?";
            sql1+=" AND tolp.Fun_level_two = ?";
            obj.add(f2);
        }
        if(!"全部".equals(f3)){
            sql0+=" AND tolp.Oper_type = ?";
            sql1+=" AND tolp.Oper_type = ?";
            obj.add(f3);
        }
        if(!"全部".equals(status)){
            sql0+=" AND tol.`Status` = ?";
            sql1+=" AND tol.`Status` = ?";
            obj.add(status);
        }
        //user id为空则为超级用户
        if(!StringUtil.isEmpty(userId)){
            sql0+=" AND tu.id = ?";
            sql1+=" AND tu.id = ?";
            obj.add(userId);
        }
        //
        if(!StringUtil.isEmpty(queryKey)){
            sql0+=" AND tol.Oper_Object_name LIKE ?";
            sql1+=" AND tol.Oper_Object_name LIKE ?";
            obj.add("%" +queryKey+"%");
        }
        List<Map<String, Object>> r=jdbcTemplate.queryForList(sql0,obj.toArray());
        int count=Integer.parseInt(r.get(0).get("num").toString());
        int r0=count/PAGE_SIZE;
        int r1=count%PAGE_SIZE;
        if(r1!=0){
            r0+=1;
        }
        operLog.setTotalPage(r0);
        obj.add((currentPage - 1) * PAGE_SIZE);
        obj.add(PAGE_SIZE);
        r=jdbcTemplate.queryForList(sql1+sql2,obj.toArray());
        operLog.setOperLogs(r);
        return operLog;
    }
}
